package com.pets.springboot_petshop.controller;

import com.pets.springboot_petshop.entity.*;
import com.pets.springboot_petshop.pojo.Result;
import com.pets.springboot_petshop.service.*;
import com.pets.springboot_petshop.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * @Author: wxk
 * @Email: 2089967794@qq.com
 * @Date: 2024/10/15 下午1:44 周二
 * @Description: 订单编号控制层
 */
@RestController
@RequestMapping("/Order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private ShoppingcartService shoppingcartService;
    @Autowired
    private OrderproductService orderproductService;
    @Autowired
    private UseraddressService useraddressService;
    //id查询
    @GetMapping("select")
    private Result select(@RequestParam int id) {
        // 获取订单
        Order order = orderService.select(id);
        if (order != null) {
            // 为订单获取商品数据
            List<Orderproduct> products = orderproductService.selectorder_id(order.getId());
            order.setOrderProducts(products);
            return Result.success(order);
        } else {
            return Result.error("获取失败");
        }
    }
    @GetMapping("selectordernumber")
    private Result selectordernumber(@RequestParam int ordernumber) {
        // 获取订单
        List<Order> orders = orderService.selectordernumber(ordernumber);
        if (orders != null) {
            // 为每个订单获取商品数据
            orders.forEach(order -> {
                List<Orderproduct> products = orderproductService.selectorder_id(order.getId());
                order.setOrderProducts(products);
            });
            return Result.success(orders);
        } else {
            return Result.error("获取失败");
        }
    }

    // 根据日期查询订单
    @GetMapping("/selectorderbydate")
    public Result selectorderbydate(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        // 获取订单
        List<Order> orders = orderService.selectOrderByDate(date);
        if (orders != null) {
            // 为每个订单获取商品数据
            orders.forEach(order -> {
                List<Orderproduct> products = orderproductService.selectorder_id(order.getId());
                order.setOrderProducts(products);
            });
            return Result.success(orders);
        } else {
            return Result.error("获取失败");
        }
    }
    // 获取年度每个月的总盈利
    @GetMapping("/selectMonthlyProfit")
    public Result getMonthlyProfit(@RequestParam int year) {
        List<MonthlyProfit> monthlyProfits = orderService.selectMonthlyProfit(year);
        return Result.success(monthlyProfits);
    }
    // 获取当月每天的盈利
    @GetMapping("/selectDailyProfit")
    public Result getDailyProfit(@RequestParam int year, @RequestParam int month) {
        List<DailyProfit> dailyProfits = orderService.selectDailyProfit(year, month);
        return Result.success(dailyProfits);
    }
    // 获取每个月的退货率
    @GetMapping("/monthly-refund-rates")
    public List<MonthlyProfit> getMonthlyRefundRates(@RequestParam int year) {
        return orderService.selectMonthlyRefundRate(year);
    }

    // 获取年度退货率
    @GetMapping("/annual-refund-rate")
    public MonthlyProfit getAnnualRefundRate(@RequestParam int year) {
        List<MonthlyProfit> annualRefundRates = orderService.selectAnnualRefundRate(year);
        if (annualRefundRates.isEmpty()) {
            return null; // 或者抛出一个异常，或者返回一个错误信息
        }
        // 假设selectAnnualRefundRate方法返回的列表中只有一个元素，即年度退货率
        return annualRefundRates.get(0);
    }

    //user_id查询
    @GetMapping("selectuser_id")
    private Result selectuser_id(@RequestHeader(name = "Authorization") String token) {
        Map<String,Object> map = JwtUtil.parseToken(token);
        int user_id = (int) map.get("id");
        User user1 = userService.select(user_id);
        if (user1 == null) {
            return Result.error("用户不存在");
        }
        List<Order> orders = orderService.selectuser_id(user_id);
        if (orders != null) {
            // 为每个订单获取商品数据
            orders.forEach(order -> {
                List<Orderproduct> products = orderproductService.selectorder_id(order.getId());
                order.setOrderProducts(products);
            });
            return Result.success(orders);
        } else {
            return Result.error("获取失败");
        }
    }
    @GetMapping("selectstatus")
    private Result selectstatus(@RequestParam String status) {
        List<Order> order = orderService.selectstatus(status);
        if (order != null) {
            return Result.success(order);
        }else {
            return Result.error("获取失败");
        }
    }
    //查询所有
    @GetMapping("/findAll")
    private Result findAll() {
        List<Order> order = orderService.findAll();
        if(order == null || order.isEmpty()){
            return Result.error("获取失败");
        }else {
            return Result.success(order);
        }
    }
    //添加
//    @PostMapping("add")
//    private Result add(@RequestBody Order order) {
//        if (orderService.add(order)>0){
//            return Result.success("新增成功");
//        }else {
//            return Result.error("获取失败");
//        }
//    }
    @PostMapping("/add")
    public Result add(@RequestBody Order order, @RequestHeader(name = "Authorization") String token) {
        // 根据令牌查询相应的用户信息
        Map<String,Object> map = JwtUtil.parseToken(token);
        int user_id = (int) map.get("id");
        // 检查用户是否存在
        User user = userService.select(user_id);
        if (user == null) {
            return Result.error("用户不存在");
        } else {
            order.setUser_id(user_id);
            order.setStatus("未发货");
            order.setDiscount(user.getDiscount());
            List<Orderproduct> orderProducts = order.getOrderProducts();
            if (orderService.addOrderWithProducts(order, orderProducts) != null && orderProducts != null) {
                if (shoppingcartService.delete(user_id)>0){
                    return Result.success(order);
                }else {
                    return Result.error("订单失败");
                }
            } else {
                return Result.error("订单失败");
            }
        }
    }
    @PostMapping("/adminadd")
    public Result adminadd(@RequestBody Order order) {
        String email = order.getEmail();
        User user = userService.findByUseremail(email);
        if (user == null) {
            String username = order.getUsername();
            String phone = order.getPhone();
            userService.addadmin(username, phone, email);

            User user1 = userService.findByUseremail(email);
            if (user1 == null) {
                return Result.error("订单失败");
            }
            int user_id = user1.getId();
            Useraddress useraddress = new Useraddress();
            useraddress.setUser_id(user_id);
            useraddress.setName(username);
            useraddress.setAddress_line1(order.getAddress_line1());
            useraddress.setAddress_line2(order.getAddress_line2());
            useraddress.setPhone(phone);
            int addedUseraddressId = useraddressService.add(useraddress);
            if (addedUseraddressId <= 0) {
                return Result.error("订单失败");
            }
            // 将useraddress_id放入order里
            order.setUseraddress_id(useraddress.getId());

            order.setUser_id(user_id);
            order.setStatus("未发货");
            List<Orderproduct> orderProducts = order.getOrderProducts();
            if (orderService.addOrderWithProducts(order, orderProducts) != null && orderProducts != null) {
                    return Result.success(order);
            } else {
                return Result.error("订单失败");
            }
        } else {
            int user_id = user.getId();
            Useraddress useraddress = new Useraddress();
            useraddress.setUser_id(user_id);
            useraddress.setName(order.getUsername());
            useraddress.setAddress_line1(order.getAddress_line1());
            useraddress.setAddress_line2(order.getAddress_line2());
            useraddress.setPhone(order.getPhone());
            int addedUseraddressId = useraddressService.add(useraddress);
            if (addedUseraddressId <= 0) {
                return Result.error("订单失败");
            }
            // 将useraddress_id放入order里
            order.setUseraddress_id(useraddress.getId());

            order.setUser_id(user_id);
            order.setStatus("未发货");
            List<Orderproduct> orderProducts = order.getOrderProducts();
            if (orderService.addOrderWithProducts(order, orderProducts) != null && orderProducts != null) {
                    return Result.success(order);
            } else {
                return Result.error("订单失败");
            }
        }
    }
    @PostMapping("/oneadd")
    public Result oneadd(@RequestBody Order order, @RequestHeader(name = "Authorization") String token) {
        // 根据令牌查询相应的用户信息
        Map<String,Object> map = JwtUtil.parseToken(token);
        int user_id = (int) map.get("id");
        // 检查用户是否存在
        User user = userService.select(user_id);
        if (user == null) {
            return Result.error("用户不存在");
        } else {
            order.setUser_id(user_id);
            order.setStatus("未发货");
            List<Orderproduct> orderProducts = order.getOrderProducts();
            if (orderService.addOrderWithProducts(order, orderProducts) != null && orderProducts != null) {
                return Result.success(order);
            } else {
                return Result.error("订单失败");
            }
        }
    }

    //删除
    @PostMapping("delete")
    private Result delete(@RequestParam Integer id){
        if (orderService.delete(id)>0){
            return Result.success("删除成功");
        }else {
            return Result.error("删除失败");
        }
    }
    //修改数据
    @PostMapping("update")
    private Result update(@RequestBody Order order){
        if (orderService.update(order)>0){
            return Result.success("修改成功");
        }else {
            return Result.error("修改失败");
        }
    }
    //管理员修改数据
    @PostMapping("adminupdate")
    private Result adminupdate(@RequestBody Order order){
        if (orderService.adminupdate(order)>0){
            int useraddress_id = order.getUseraddress_id();
            String address_line1 = order.getAddress_line1();
            String address_line2 = order.getAddress_line2();
            String phone = order.getPhone();
            String name = order.getName();
            Useraddress useraddress = new Useraddress();
            useraddress.setId(useraddress_id);
            useraddress.setAddress_line1(address_line1);
            useraddress.setAddress_line2(address_line2);
            useraddress.setPhone(phone);
            useraddress.setName(name);
            if ( useraddressService.update(useraddress)>0){
                return Result.success("修改成功");
            }else {
                return Result.error("修改失败");
            }
        }else {
            return Result.error("修改失败");
        }
    }
    //修改状态
    @PostMapping("updatestatus")
    public Result updateStatus(@RequestBody Order order) {
        if ("退款中".equals(order.getStatus())) {
            Order existingOrder = orderService.select(order.getId());
            if (existingOrder == null) {
                return Result.error("订单不存在");
            }
            String currentStatus = existingOrder.getStatus();
            existingOrder.setTk_status(currentStatus);
            if (orderService.updatetk_status(existingOrder) > 0) {
                if (orderService.updatestatus(order) > 0) {
                    return Result.success("修改成功");
                } else {
                    return Result.error("数据库更新失败");
                }
            } else {
                return Result.error("更新tk_status失败");
            }
        } else {
            if (orderService.updatestatus(order) > 0) {
                return Result.success("修改成功");
            } else {
                return Result.error("订单状态不允许修改");
            }
        }
    }
    @PostMapping("updateCancel")
    public Result updateCancel(@RequestBody Order order) {
        Order existingOrder = orderService.select(order.getId());
        String currentStatus = existingOrder.getTk_status();
        existingOrder.setStatus(currentStatus);
        if (orderService.updatestatus(existingOrder) > 0) {
            return Result.success("取消退款成功");
        }else {
            return Result.error("取消退款失败");
        }
    }
    @PostMapping("adminupdatestatus")
    public Result adminupdatestatus(@RequestBody Order order) {
        Order existingOrder = orderService.select(order.getId());
        if (existingOrder == null) {
            return Result.error("订单不存在");
        }
        if (orderService.updatestatus(order) > 0) {
            return Result.success("修改成功");
        }else {
            return Result.error("修改失败");
        }
    }
    @PostMapping("/batchUpdateStatus")
    public Result batchUpdateStatus(@RequestBody Map<String, Object> payload) {
        // 从payload中获取orderIds和status
        List<Integer> orderIdList = (List<Integer>) payload.get("ids");
        String newStatus = (String) payload.get("status");
        // 将List转换为int数组
        int[] ids = new int[orderIdList.size()];
        for (int i = 0; i < orderIdList.size(); i++) {
            ids[i] = orderIdList.get(i);
        }

        // 调用service层方法执行批量更新
        int updated = orderService.batchUpdateStatus(ids, newStatus);
        return updated > 0 ? Result.success("批量更新状态成功") : Result.error("批量更新状态失败");
    }
    @PostMapping("/admindelete")
    public Result admindelete(@RequestBody Map<String, Object> payload) {
        try {
            // 从payload中获取orderIds
            List<Integer> orderIdList = (List<Integer>) payload.get("ids");
            if (orderIdList == null || orderIdList.isEmpty()) {
                return Result.error("未提供有效的ID列表");
            }

            // 将List转换为int数组
            int[] ids = new int[orderIdList.size()];
            for (int i = 0; i < orderIdList.size(); i++) {
                ids[i] = orderIdList.get(i);
            }

            int affectedRows = orderService.admindelete(ids);
            if (affectedRows > 0) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (ClassCastException e) {
            return Result.error("ID列表格式错误，应为整数数组");
        } catch (Exception e) {
            return Result.error("服务器错误：" + e.getMessage());
        }
    }

}
